﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UserInfo : MonoBehaviour {


    public GameObject student = null;
    public GameObject teacher = null;
    public GameObject courseware = null;


    // student ------------------------
    public InputField stuName = null;
    public Dropdown stuProvince = null;
    public Dropdown stuSchool = null;
    // student end --------------------

    // teacher ------------------------
    public InputField teacherName = null;
    // teacher  end -------------------


    // courseware -----------------------
    public GameObject item = null;

    public GameObject uiAudio = null;
    public Button uiAudioMansu = null;
    public Button uiAudioKuaisu = null;
    public Button uiAudioMansuPause = null;
    public Button uiAudioKuaisuPause = null;
    public AudioSource audioSource = null;
    public Button uiAudioReturn = null;

    // courseware end -------------------

    private static UserInfo instance = null;
    public static UserInfo GetInstance()
    {
        return instance;
    }

    private string nowAudioMansuUrl = "";
    private string nowAudioKuaisuUrl = "";
    private void Awake()
    {
        instance = this;

        uiAudioMansu.onClick.AddListener(() => {
            Debug.Log("clicked the audio mansu");
            ResLoader.PlayAudio(audioSource, nowAudioMansuUrl);
            uiAudioMansu.gameObject.SetActive(false);
            uiAudioKuaisu.gameObject.SetActive(true);
        });
        uiAudioKuaisu.onClick.AddListener(() => {
            ResLoader.PlayAudio(audioSource, nowAudioKuaisuUrl);
            uiAudioMansu.gameObject.SetActive(true);
            uiAudioKuaisu.gameObject.SetActive(false);
        });
        uiAudioMansuPause.onClick.AddListener(
            () => {
                audioSource.Pause();
                uiAudioMansu.gameObject.SetActive(true);
            }
            );
        uiAudioKuaisuPause.onClick.AddListener(
            () => {
                audioSource.Pause();
                uiAudioKuaisu.gameObject.SetActive(true);
            }
            );
        uiAudioReturn.onClick.AddListener(() => {
            uiAudio.SetActive(false);
        });
    }

    public void Show()
    {
        gameObject.SetActive(true);

        lessonUI.GetInstance().gameObject.SetActive(false);

        courseware.SetActive(false);
        student.SetActive(false);
        teacher.SetActive(false);

        if ( DataManager.appUserData.IsNull() )
        {
            // 试用版，直接打开课件
            OnOpenCourseware();

        }
        else if (DataManager.appUserData.type == "teacher")
        {
            teacher.SetActive(true);
            teacherName.text = DataManager.appUserData.name;
        }
        else
        {
            student.SetActive(true);
            stuName.text = DataManager.appUserData.name;

            List<string> li = DataManager.schoolData.GetAllProvince();
            stuProvince.AddOptions(li);
            

        }
    }


    public void OnProvinceValueChanged(int idx)
    {
        string v = stuProvince.options[idx].text;
        string[] s = v.Split(',');

        NetMgr.ReqSchool(s[0], s[1], s[2], (suc, sd) => {

            if (suc)
            {
                List<string> l = sd.GetAllOrgnazationName();
                stuSchool.ClearOptions();
                stuSchool.AddOptions(l);
            }
            else
            {
                Tips.ShowBottomTip("error", Color.red, 3f);
            }


        });
    }

    public void Hide()
    {
        gameObject.SetActive(false);
        lessonUI.GetInstance().gameObject.SetActive(true);
    }

    public void OnClearCache()
    {
        ClearCache.Show(false);
    }

    public void OnClearCourseware()
    {
        ClearCache.Show(true);
    }


    public void OnOpenCourseware()
    {
        student.SetActive(false);
        teacher.SetActive(false);
        courseware.SetActive(true);


        // 初始化课件
        InitCourseware();
    }

    public void OnBackFromCourseware()
    {
        //        courseware.SetActive(false);
        if ( DataManager.appUserData.IsNull() )
        {
            // 试用版，返回lessonui
            OnBack();
        }
        else
            Show();
    }

    public void OnBack()
    {
        gameObject.SetActive(false);

        lessonUI.GetInstance().gameObject.SetActive(true);
        lessonUI.GetInstance().ShowLessonList();
    }

    public void OnCommit()
    {
        // commit
        if ( DataManager.appUserData.type == "teacher")
        {
            string newname = teacherName.text;
            NetMgr.ReqUpdateAppUserById(DataManager.appUserData.id, null, newname, (suc, msg) => {
                if (suc)
                {
                    Tips.ShowBottomTip(msg, Color.black, 3f);
                    OnBack();
                }
                else
                {
                    Tips.ShowBottomTip(msg, Color.red, 3f);
                }
            });
        }
        else
        {
            string newname = stuName.text;
            string orgid = DataManager.schoolsData.GetIDByName(stuSchool.options[stuSchool.value].text);
            NetMgr.ReqUpdateAppUserById(DataManager.appUserData.id, orgid, newname, (suc, msg) => {
                if (suc)
                {
                    Tips.ShowBottomTip(msg, Color.black, 3f);
                    OnBack();
                }
                else
                {
                    Tips.ShowBottomTip(msg, Color.red, 3f);
                }
            });
        }

    }

    public void InitCourseware()
    {
        // 清除之前的选项
        for( int i = 1; i < item.transform.parent.childCount; i++ )
        {
            Transform t = item.transform.parent.GetChild(i);
            Destroy(t.gameObject);
        }

        // 
        foreach (var it in DataManager.kejianCfgData.d)
        {
            GameObject go = Instantiate(item);
            go.SetActive(true);
            go.transform.parent = item.transform.parent;
            go.transform.localScale = item.transform.localScale;

            go.name = it.Key;

            CoursewareItem ci = go.GetComponent<CoursewareItem>();
            // 取得text
//            Text t = go.GetComponentInChildren<Text>();
//            t.text = "第" + it.Key + "课";

            ci.title.text = "第" + it.Key + "课";

            // bind video
            ci.openVi.onClick.AddListener(() => {

                string sv = null;
                string sa = null;
                bool suc = DataManager.kejianCfgData.GetVideoUrl(it.Key, out sv, out sa);
                if (!suc)
                {
                    return;
                }
                    


                VideoBG.PlayLocal(sv, sa);
                VideoPlayerUI.Open( gameObject );

//                Handheld.PlayFullScreenMovie("file://" + ul, Color.black, FullScreenMovieControlMode.CancelOnInput, FullScreenMovieScalingMode.AspectFill);
            });

            // bind audio
            ci.openAu.onClick.AddListener(() => {
                uiAudio.SetActive(true);
                uiAudioMansu.gameObject.SetActive(true);
                uiAudioKuaisu.gameObject.SetActive(true);

                List<string> us = DataManager.kejianCfgData.GetAudioUrl(it.Key);
                nowAudioMansuUrl = us[0];
                nowAudioKuaisuUrl = us[1];
            });


            

            // bind jiaoan
//            string urlJA = DataManager.kejianCfgData.GetPicUrl(it.Key);

            ci.openJA.onClick.AddListener(() => {
                //                ImageController.GetInstance().Open(urlJA);
                ImageController.GetInstance().Open(DataManager.kejianCfgData.GetPicUrl(it.Key));
            });

            // bind drum
            ci.openDr.onClick.AddListener(() =>
            {
                // video
                string sv = null;
                string sa = null;
                bool suc = DataManager.kejianCfgData.GetDrumUrl(it.Key, out sv, out sa);
                if (!suc)
                    return;

                VideoBG.PlayLocal(sv, sa);
                VideoPlayerUI.Open(gameObject);
            }
                );

            // bind dancing
            ci.openDa.onClick.AddListener(() =>
            {
                // video
                string sv = null;
                string sa = null;
                bool suc = DataManager.kejianCfgData.GetDancingUrl(it.Key,out sv, out sa);
                if (!suc)
                    return;

                VideoBG.PlayLocal(sv, sa);
                VideoPlayerUI.Open(gameObject);
            }
                );

            // 课件url是否下载
            if (it.Value.kejian.Count > 0 && string.IsNullOrEmpty(it.Value.kejian[0]) == false)
            {
                if (ResLoader.HaveDownload(it.Value.kejian[0]) == false)
                {
                    ci.btnDownJiaoan.SetActive(true);
                    // 没有下载打开下载按钮
                    //                    Transform tr = go.transform.Find("downjiaoan");
                    //                    if (tr != null)
                    //                        tr.gameObject.SetActive(true);
                    ci.downJA.onClick.AddListener(() =>
                    {
                        ClearCache.AddCacheCourseware(it.Key);
                        OnDownload( ci.downJA.gameObject, it.Value.kejian);
                    });
                }
            }
            else
            {
                ci.openJA.gameObject.SetActive(false);
            }

            // 音频url是否下载
            if (it.Value.audio.Count > 0 && (string.IsNullOrEmpty(it.Value.audio[0]) == false || string.IsNullOrEmpty(it.Value.audio[1]) == false))
            {
                if (ResLoader.HaveDownload(it.Value.audio[0]) == false || ResLoader.HaveDownload(it.Value.audio[1]) == false )
                {
                    ci.btnDownAudio.SetActive(true);
                    // 没有下载打开下载按钮
                    //                    Transform tr = go.transform.Find("downaudio");
                    //                    if (tr != null)
                    //                        tr.gameObject.SetActive(true);
                    ci.downAu.onClick.AddListener(() => {

                        ClearCache.AddCacheCourseware(it.Key);
                        OnDownload(ci.downAu.gameObject, it.Value.audio);
                    });
                }

            }
            else
            {
                ci.openAu.gameObject.SetActive(false);
            }

            // 视频url是否下载
            if (it.Value.video.Count > 0 && string.IsNullOrEmpty(it.Value.video[0]) == false)
            {
                if (ResLoader.HaveDownload(it.Value.video[0]) == false)
                {
                    ci.btnDownVideo.SetActive(true);
                    // 没有下载打开下载按钮
                    //                    Transform tr = go.transform.Find("downvideo");
                    //                    if (tr != null)
                    //                        tr.gameObject.SetActive(true);

                    ci.downVi.onClick.AddListener(() => {

                        ClearCache.AddCacheCourseware(it.Key);
                        OnDownload(ci.downVi.gameObject, it.Value.video);
                    });
                }

            }
            else
            {
                ci.openVi.gameObject.SetActive(false);
            }

            // drum url是否下载
            if (it.Value.drum.Count > 0 && string.IsNullOrEmpty(it.Value.drum[0]) == false)
            {
                if (ResLoader.HaveDownload(it.Value.drum[0]) == false)
                {
                    ci.btnDownDrum.SetActive(true);
                    // 没有下载打开下载按钮
                    //                    Transform tr = go.transform.Find("downvideo");
                    //                    if (tr != null)
                    //                        tr.gameObject.SetActive(true);

                    ci.downDr.onClick.AddListener(() => {

                        ClearCache.AddCacheCourseware(it.Key);
                        OnDownload(ci.downDr.gameObject, it.Value.drum);
                    });
                }

            }
            else
            {
                ci.openDr.gameObject.SetActive(false);
            }

            // dancing url是否下载
            if (it.Value.dancing.Count > 0 && string.IsNullOrEmpty(it.Value.dancing[0]) == false)
            {
                if (ResLoader.HaveDownload(it.Value.dancing[0]) == false)
                {
                    ci.btnDownDancing.SetActive(true);
                    // 没有下载打开下载按钮
                    //                    Transform tr = go.transform.Find("downvideo");
                    //                    if (tr != null)
                    //                        tr.gameObject.SetActive(true);

                    ci.downDa.onClick.AddListener(() => {
                        ClearCache.AddCacheCourseware(it.Key);
                        OnDownload(ci.downDa.gameObject, it.Value.dancing);
                    });
                }

            }
            else
            {
                ci.openDa.gameObject.SetActive(false);
            }

            if ( DataManager.appUserData.IsNull() )
            {
                // 试用版，只显示一课
                break;
            }
        }
    }


    void OnDownload(GameObject sender, List<string> li )
    {
        int count = 1;
        int total = li.Count;

        
        foreach( var item in li )
        {
            ResLoader.Load(item,
                (progress) => {
                    //
                    downloadProgress.Show(progress, count, total);
                },
                (res) => {
                    count++;
                    if (count >= total)
                    {
                        // finish
                        // 可以进入
                        downloadProgress.Hide();

                        // 下载按钮消失
                        sender.SetActive(false);
                    }
                }, true, true);
        }

            
        
    }

    public void OnBtnDownload()
    {

    }

    public void OnBtnQuitLogin()
    {
        DataManager.appUserData.Clear();

        OnBack();

        Index.GetInstance().gameObject.SetActive(true);
    }

}
